package cn.com.acca.ma.service.impl;

import cn.com.acca.ma.common.util.PropertiesUtil;
import cn.com.acca.ma.model.ModelStockAnalysis;
import cn.com.acca.ma.model.StockWeek;
import cn.com.acca.ma.service.ModelStockAnalysisService;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RectangleInsets;

import java.awt.*;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ModelStockAnalysisServiceImpl extends BaseServiceImpl<ModelStockAnalysisServiceImpl, ModelStockAnalysis> implements
        ModelStockAnalysisService {

    /**
     * 计算model_stock_analysis表的全部数据
     */
    @Override
    public void writeModelStockAnalysis() {
        modelStockAnalysisDao.writeModelStockAnalysis();
    }

    /**
     * 计算model_stock_analysis表的某一日的数据
     *
     * @param multithreading
     */
    @Override
    public void writeModelStockAnalysisByDate(boolean multithreading) {
        String stockAnalysisDate = PropertiesUtil.getValue(MODEL_STOCK_ANALYSIS, "stock.analysis.date");
        modelStockAnalysisDao.writeModelStockAnalysisByDate(multithreading, stockAnalysisDate);
    }

    /**
     * 创建日线级别标准差和平均收盘价的折线图
     */
    @Override
    public void createModelStockAnalysisStandardDeviationPictureAndAverageClosePrice() {
        String beginDate = PropertiesUtil.getValue(MODEL_STOCK_ANALYSIS_PICTURE, "stock.analysis.standardDeviation.AverageClosePrice.beginDate");
        String endDate = PropertiesUtil.getValue(MODEL_STOCK_ANALYSIS_PICTURE, "stock.analysis.standardDeviation.AverageClosePrice.endDate");

        // 根据开始时间和结束时间，计算每个交易日、所有股票的平均收盘价和平均方差，并按时间升序排列
        List<Object> list = modelStockAnalysisDao.findAverageClosePriceAndAverageStandardDeviationByBeginDateAndEndDateOrderByDate(beginDate, endDate);

        TimeSeries averageClosePriceTimeSeries = new TimeSeries("平均收盘价", org.jfree.data.time.Day.class);
        TimeSeries averageStandardDeviationTimeSeries = new TimeSeries("平均方差", org.jfree.data.time.Day.class);
        TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();

        if (null != list && list.size() > 0) {
            for (Object object : list) {
                Object[] objectArray = (Object[]) object;
                BigDecimal averageClosePrice = (BigDecimal) objectArray[0];
                BigDecimal averageStandardDeviation = (BigDecimal) objectArray[1];
                BigDecimal maxAverageClosePrice = (BigDecimal) objectArray[2];
                BigDecimal minAverageClosePrice = (BigDecimal) objectArray[3];
                BigDecimal maxAverageStandardDeviation = (BigDecimal) objectArray[4];
                BigDecimal minAverageStandardDeviation = (BigDecimal) objectArray[5];
                Date date = (Date) objectArray[6];

                averageClosePriceTimeSeries.addOrUpdate(new Day(date), averageClosePrice.doubleValue());
//                averageClosePriceTimeSeries.addOrUpdate(new Day(date), this.adjustData(maxAverageClosePrice.doubleValue(), minAverageClosePrice.doubleValue(), maxAverageStandardDeviation.doubleValue(), minAverageStandardDeviation.doubleValue(), averageClosePrice.doubleValue() * 2));
//                averageStandardDeviationTimeSeries.addOrUpdate(new Day(date), averageStandardDeviation);
                averageStandardDeviationTimeSeries.addOrUpdate(new Day(date), this.adjustData(maxAverageStandardDeviation.doubleValue(), minAverageStandardDeviation.doubleValue(), maxAverageClosePrice.doubleValue(), minAverageClosePrice.doubleValue(), averageStandardDeviation.doubleValue()));
            }
        }

        timeSeriesCollection.addSeries(averageClosePriceTimeSeries);
        timeSeriesCollection.addSeries(averageStandardDeviationTimeSeries);

        // 配置字体
        // X轴字体
        Font xFont = new Font("宋体", Font.PLAIN, 30);
        // Y轴字体
        Font yFont = new Font("宋体", Font.PLAIN, 30);
        // 底部字体
        Font bottomFont = new Font("宋体", Font.PLAIN, 30);
        // 图片标题字体
        Font titleFont = new Font("隶书", Font.BOLD, 40);

        JFreeChart jfreechart = ChartFactory.createTimeSeriesChart("日线级别所有股票的平均收盘价和平均方差",
                "日期", "平均收盘价和平均方差", timeSeriesCollection, true, true, true);

        jfreechart.setBackgroundPaint(Color.white);
        // 图片标题
        jfreechart.setTitle(new TextTitle(jfreechart.getTitle().getText(), titleFont));
        // 底部字体
        jfreechart.getLegend().setItemFont(bottomFont);

        XYPlot xyPlot = (XYPlot) jfreechart.getPlot();
        xyPlot.setBackgroundPaint(Color.lightGray);
        xyPlot.setDomainGridlinePaint(Color.white);
        xyPlot.setRangeGridlinePaint(Color.white);
        xyPlot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
        xyPlot.setDomainCrosshairVisible(true);
        xyPlot.setRangeCrosshairVisible(true);
        xyPlot.getDomainAxis();

        // X轴
        ValueAxis domainAxis = xyPlot.getDomainAxis();
        // X轴标题字体
        domainAxis.setLabelFont(xFont);
        // Y轴
        ValueAxis rangeAxis = xyPlot.getRangeAxis();
        // Y轴标题字体
        rangeAxis.setLabelFont(yFont);

        org.jfree.chart.renderer.xy.XYItemRenderer xyItemRenderer = xyPlot.getRenderer();
        // 设置所有线条粗细
        xyItemRenderer.setStroke(new BasicStroke(3.0F));
        if (xyItemRenderer instanceof XYLineAndShapeRenderer) {
            XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyItemRenderer;
            xylineandshaperenderer.setBaseShapesVisible(true);
            xylineandshaperenderer.setBaseShapesFilled(true);
            xylineandshaperenderer.setSeriesPaint(2, Color.BLACK);
        }
        DateAxis dateaxis = (DateAxis) xyPlot.getDomainAxis();
        dateaxis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));

        try {
            FileOutputStream fos = new FileOutputStream(PICTURE_PATH + "model_stock_analysis_average_close_price_and_average_standard_deviation/" + beginDate + "-" + endDate + PICTURE_FORMAT);
            // 将统计图标输出成JPG文件
            ChartUtilities.writeChartAsJPEG(fos, // 输出到哪个输出流
                    1, // JPEG图片的质量，0~1之间
                    jfreechart, // 统计图标对象
                    1800, // 宽
                    1000,// 宽
                    null // ChartRenderingInfo 信息
            );
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Override
    public String listToString(List list) {
        return null;
    }
}

